define(['moment'], function (moment) {
    return ['$scope', '$rootScope', '$mdDialog', 'MMWService', '$filter', '$stateParams', '$timeout', 'config',
        function ($scope, $rootScope, $mdDialog, $MMWService, $filter, $stateParams, $timeout, config) {
            // 流程
            $scope.phases = [
                'process_machine',
                'process_plot_no',
                'process_tool'
            ];

            $scope.init = function(){
                $scope.user_name = config.cache.name;
                $scope.envInfo = $filter('translate')('Login.env.'+config.setting.environment);
                $scope.item_list = [];
                $scope.start_condition = [];
                // 預設流程狀態
                $scope.phases_index = 0;

                // 自動隱蔽鍵盤
                element_barcode_no = document.getElementById('input_barcode');
                makeBarcodeInput(element_barcode_no);
                element_barcode_no.focus();
            };

            $scope.back = function(){
                $scope.$root.hideMenu();
                $scope.$root.changeProgram('menu', true);
            };

            // QRCode輸入
            $scope.QRCodeScanner = function(){
                $scope.$root.OpenScanner({
                    after : function(result){
                        input_barcode_no_callback(result.text);
                    },
                    exception: function(){
                        //目前裝置無法使用相機
                        $scope.$root.showAlert($filter('translate')('common.msg.cant_use_camera'));
                    },
                    orientation : 'portrait'
                });
            };

            // barcode輸入
            $scope.input_barcode = function(barcode){
                input_barcode_no_callback(barcode);
            };

            // 流程狀態
            $scope.PhaseStatus = function(index){
                if($scope.phases_index > index)
                    return ['prev'];
                else if($scope.phases_index == index)
                    return ['now'];
                else
                    return ['next'];
            };

            // 回上一步流程
            $scope.BackToPhase = function (index){
                if($scope.phases_index > index){
                    var _temp = $filter('filter')($scope.item_list, {status:'N'});
                    if(_temp && _temp.length > 0){
                        $scope.$root.showConfirm($filter('translate')('SMT08.msg.leave_but-data-disappear'),function(dialog){
                            dialog.hide();
                            BackToPhase(index);
                        });
                    } else {
                        BackToPhase(index);
                    };
                };
            };

            // 回上一步流程 callback
            function BackToPhase(index){
                $scope.phases_index = index;
                if(index == 0){
                    $scope.machine_no = '';
                    $scope.plot_no = '';
                    $scope.plot_product_no = '';
                    $scope.plot_item_spec = '';
                    $scope.item_list = [];
                } else if($scope.phases_index == 1){
                    $scope.plot_no = '';
                    $scope.plot_product_no = '';
                    $scope.plot_item_spec = '';
                    $scope.start_conditions = [];
                    //$scope.item_list = [];
                };
            };

            // barcode輸入 callback
            function input_barcode_no_callback(barcode){
                if(barcode != ''){
                    // 設備流程
                    if($scope.phases_index == 0){
                        machine_info_get(barcode);
                    // 生產批流程
                    } else if($scope.phases_index == 1) {
                        if($scope.is_dispatch == 0){
                            plot_info_get_dispatch_zero(barcode, function(itemList){
                                if(itemList && itemList.length > 0){
                                    $scope.plot_no = itemList[0].plot_no;
                                    $scope.plot_product_no = itemList[0].product_no;
                                    $scope.plot_item_spec = itemList[0].item_spec;
                                    $scope.plot_product_ver = itemList[0].product_ver;
                                    equipment_start_limit_info_get();
                                } else {
                                    $scope.$root.showAlert($filter('translate')('common.msg.no_data'));
                                };
                            });
                        } else if ($scope.is_dispatch == 1){
                            plot_info_get_dispatch_one(barcode, function(itemList){
                                if(itemList && itemList.length > 0){
                                    $scope.phases_index = 2;
                                    $scope.plot_no = itemList[0].plot_no;
                                    $scope.plot_product_no = itemList[0].product_no;
                                    $scope.plot_item_spec = itemList[0].item_spec;
                                    $scope.plot_product_ver = itemList[0].product_ver;
                                    equipment_start_limit_info_get();
                                } else {
                                    $scope.$root.showAlert($filter('translate')('common.msg.no_data'));
                                };
                            });
                        };
                    // 工具上線
                    } else if($scope.phases_index == 2){
                        tool_info_get(barcode, function(itemList){
                            if(itemList && itemList.length > 0){
                                // 不能重複輸入已經存在的工具編號
                                var isRepeat;
                                isRepeat = $filter('filter')($scope.item_list, {tool_no:itemList[0].tool_no}, true);
                                if(isRepeat && isRepeat.length > 0){
                                    return $scope.$root.showAlert($filter('translate')('SMT08.msg.enter_the_same_tool_repeatedly'))
                                };
                                
                                var _temp = $filter('filter')($scope.start_conditions, {tooltype_no:itemList[0].tooltype_no}, true);
                                if(_temp&&_temp.length > 0){
                                    var check_bool = false;
                                    // 工具需求數量等於 0，則不用卡控此設備已上線的工具數量，可以輸入多個工具序號。
                                    if(_temp[0].tool_qty == 0){
                                        check_bool = true;
                                    } else if (_temp[0].now_qty < _temp[0].tool_qty){
                                        check_bool = true;
                                    } else {
                                        // 工具需求數量已達上限
                                        $scope.$root.showAlert(_temp[0].tooltype_no + ' ' + $filter('translate')('SMT08.msg.tool_qty_limit'));
                                    };

                                    if(check_bool){
                                        $scope.item_list.unshift({
                                            equipment_no: $scope.machine_no,
                                            status: 'N',
                                            tooltype_no: itemList[0].tooltype_no,
                                            tool_type: itemList[0].tool_class,
                                            tool_no: itemList[0].tool_no,
                                            insert_time:Date.now(),
                                            tool_handle_type: '60',
                                            // 傳入產品編號和產品版本，後台才能卡控工具需求數量有達到上限
                                            product_no: $scope.plot_product_no,
                                            product_ver: $scope.plot_product_ver
                                        });
                                    }
                                } else {
                                    //此設備不需要上線此工具
                                    $scope.$root.showAlert($filter('translate')('SMT08.msg.tool_not_in_conditon') + barcode);
                                }
                            } else {
                                $scope.$root.showAlert($filter('translate')('common.msg.no_data'));
                            }
                        });
                    } else {
                        $scope.$root.showAlert($filter('translate')('common.msg.no_data'));
                    };
                };
            };

            // 刪除工具流程項目
            $scope.removeRow = function (item) {
                $scope.item_list.splice($scope.item_list.indexOf(item), 1);
            };

            // 點擊確認按鈕轉換狀態為 y
            $scope.confirm = function(){
                var content = {
                    // 因為是用 unshift 的方式增加的，所以如果刷超過工具需求數量，後台雖然會卡控，但送過去的資料要反轉(reverse)才能按照刷入的順序送。
                    tool_details: $filter('filter')($scope.item_list, {status:'N'}, true).reverse()
                };
                tool_handle_set_process(content, function(data){
                    if(data && data.length > 0){
                        // 刷入工具，後台回傳的訊息
                        var msg = '';
                        for(var i = 0; i < data.length; i++){
                            if(data[i].status == 'E' && data[i].result.length > 0)
                                msg += '<label style="display: block; padding: 3px 0;">' + data[i].tool_no + data[i].result + '</label>';      
                        }
                        if(msg == '')
                            $scope.$root.showToast($filter('translate')('SMT08.msg.success'));
                        else
                            $scope.$root.showAlert(msg);   
                    }
                    $MMWService.pageNumberInfoGet({
                        page_mode : 'tool_info_get',
                        query_condition_info:[
                            {column_name:'EquipmentNo', query_mode:'0', value: $scope.machine_no, merge_condition_model:'AND'},
                        ]
                    }, function(itemList){
                        // 按下確定後，重新透過服務，重取工具資料。
                        $scope.item_list = itemList;
                        $scope.start_conditions.forEach(function(condition){
                            var _temp = $filter('filter')($scope.item_list, {tooltype_no:condition.tooltype_no}, true);
                            condition.now_qty = _temp.length;
                        });
                    });
                });
            };

            // 取得 設備資料
            function machine_info_get(machine_no, callback){
                $MMWService.pageNumberInfoGet({
                    page_mode : 'smt_equipment_info_get',
                    query_condition_info:[
                        {column_name:'a.EquipmentNo', query_mode:'0', value: machine_no, merge_condition_model:'AND'},
                    ]
                }, function(itemList){
                    if(itemList && itemList.length > 0){
                        $scope.phases_index = 1;
                        $scope.machine_no = itemList[0].equipment_no;
                        $scope.area_no = itemList[0].area_no;
                        $scope.is_dispatch = itemList[0].is_dispatch;
                        $MMWService.pageNumberInfoGet({
                            page_mode : 'tool_info_get',
                            query_condition_info:[
                                {column_name:'EquipmentNo', query_mode:'0', value: $scope.machine_no, merge_condition_model:'AND'},
                            ]
                        }, function(itemList){
                            $scope.item_list = itemList;
                        });
                    } else {
                        $scope.$root.showAlert($filter('translate')('common.msg.no_data'));
                    };
                });
            };

            // 取得 生產批資料 (is_dispatch = 0)
            function plot_info_get_dispatch_zero(plot_no, callback){
                $MMWService.pageNumberInfoGet({
                    page_mode : 'equipment_queue_info_get',
                    query_condition_info:[
                        {column_name:'a.AreaNo', query_mode:'0', value: $scope.area_no, merge_condition_model:'AND'},
                        {column_name:'b.BaseLotNo', query_mode:'0', value: plot_no, merge_condition_model:'AND'}
                    ]
                }, function(itemList){
                    if(callback)
                        callback(itemList);
                });
            };

            // 取得 生產批資料 (is_dispatch = 1)
            function plot_info_get_dispatch_one(plot_no, callback){
                $MMWService.pageNumberInfoGet({
                    page_mode : 'equipment_dispatch_queue_info_get',
                    query_condition_info:[
                        {column_name:'a.EquipmentNo', query_mode:'0', value: $scope.area_no, merge_condition_model:'AND'},
                        {column_name:'b.BaseLotNo', query_mode:'0', value: plot_no, merge_condition_model:'AND'}
                    ]
                }, function(itemList){
                    if(callback)
                        callback(itemList);
                });
            };

            // 取得 開機條件
            function equipment_start_limit_info_get(){
                $MMWService.pageNumberInfoGet({
                    page_mode : 'equipment_start_limit_info_get',
                    query_condition_info:[
                        {column_name:'a.EquipmentNo', query_mode:'0', value: $scope.machine_no, merge_condition_model:'AND'},
                        {column_name:'a.ProductNo', query_mode:'0', value: $scope.plot_product_no, merge_condition_model:'AND'},
                        {column_name:'a.ProductNo', query_mode:'0', value:'ALL'},
                        {column_name:'a.ProductVer', query_mode:'0', value: $scope.plot_product_ver, merge_condition_model:'AND'},
                        {column_name:'a.ProductVer', query_mode:'0', value: '*'}
                    ]
                }, function(itemList){
                    //add by a991241234 for M#69873
                    //調整產品編號 判斷 如果開機條件取不到自己產品編號版本 就取看看有沒有 * 號設定 如果都沒有就取 ALL
                    var temp_itemList_1 = $filter('filter')(itemList, {product_ver:$scope.plot_product_ver,product_no:$scope.plot_product_no}, true);
                    var temp_itemList_2 = $filter('filter')(itemList, {product_ver:'*',product_no:$scope.plot_product_no}, true);
                    var temp_itemList_3 = $filter('filter')(itemList, {product_ver:'*',product_no:'ALL'}, true);
                    if(temp_itemList_1.length == 0)
                    {
                        if(temp_itemList_2.length == 0)
                            itemList = temp_itemList_3;
                        else
                            itemList = temp_itemList_2;
                    }  
                    else
                        itemList = temp_itemList_1;
                    itemList = itemList.filter(function(item)
                    {
                       return (item.tooltype_no != "" && item.tool_qty !="");
                    });
                    if(itemList && itemList.length > 0){
                        $scope.phases_index = 2;
                        $scope.start_conditions = itemList;
                        $scope.start_conditions.forEach(function(condition){
                            var _temp = $filter('filter')($scope.item_list, {tooltype_no:condition.tooltype_no}, true);
                            condition.now_qty = _temp.length;
                        });
                    } else {
                        $scope.$root.showAlert($filter('translate')('SMT08.msg.machine_without_starting_condition'));
                    }
                });
            };

            // 取回 工具資訊
            function tool_info_get(tool_no, callback){
                $MMWService.pageNumberInfoGet({
                    page_mode : 'tool_info_get',
                    query_condition_info:[
                        {column_name:'ToolNo', query_mode:'0', value: tool_no, merge_condition_model:'AND'},
                    ]
                }, function(itemList){
                    if(callback)
                        callback(itemList);
                });
            }

            // 送回 工具資料
            function tool_handle_set_process(content, callback){
                $MMWService.sendToServer({
                    uri : 'ServicesSMT.Module_SMT.tool_handle_set_process',
                    content : content,
                    success : function(data){
                        if(callback)
                            callback(data);
                    }
                });
            };
            
            $scope.input_PDA_barcode = function(event){
                if (event.keyCode == 13) {
                    element_barcode_no.blur();
                    input_barcode_no_callback($scope.barcode)
                    $scope.barcode = '';
                } else {
                    $scope.barcode = $scope.barcode || '';
                }
            }

            //20200914 modify by Dustdusk for M#: 增加
            function makeBarcodeInput(el) {
                var _input = el.getElementsByClassName('barcode_input')[0];
                //var _mask = el.getElementsByClassName('barcode_mask')[0];
                el.focus = function () {
                    //e.preventDefault();
                    //_mask.click();
                    el.click();
                }
                el.addEventListener('click', function (e) {
                    e.preventDefault();
                    //_input.value = '';
                    if (document.activeElement !== _input)
                        _input.focus();
                });
                _input.addEventListener('focus', function (e) {
                    e.preventDefault();
                    setTimeout(function () {
                        _input.removeAttribute('readonly');
                    }, 200);
                });
                _input.addEventListener('blur', function (e) {
                    e.preventDefault();
                    _input.setAttribute('readonly', 'readonly');
                });
            }
        }
    ];
});
